<template>
	<AdminLayout activeKey="order-detail" :breadcrumbs="['首页','订单与交易管理','订单详情']" tabTitle="订单详情" :loading="isLoading">
		<view class="page">
			<view class="section-header">
				<text class="section-title">订单详情</text>
				<text class="section-desc">查看订单的完整信息和处理记录</text>
			</view>

			<!-- 订单基本信息 -->
			<view class="info-card">
				<view class="card-title">基本信息</view>
				<view class="info-grid">
					<view class="info-item">
						<text class="info-label">订单ID</text>
						<text class="info-value">{{ taskInfo._id }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">任务标题</text>
						<text class="info-value">{{ taskInfo.title }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">任务类型</text>
						<text class="info-value type-tag">{{ getTaskTypeFromTitle(taskInfo.title) }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">任务报酬</text>
						<text class="info-value reward-value">¥{{ taskInfo.reward }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">订单状态</text>
						<text class="info-value status-tag" :class="taskInfo.order_status">{{ getTaskOrderStatusText(taskInfo.order_status) }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">支付状态</text>
						<text class="info-value payment-tag" :class="getPaymentStatus(taskInfo).class">{{ getPaymentStatus(taskInfo).text }}</text>
					</view>
				</view>
			</view>

			<!-- 任务描述 -->
			<view class="info-card" v-if="taskInfo.description">
				<view class="card-title">任务描述</view>
				<view class="description-content">{{ taskInfo.description }}</view>
			</view>

			<!-- 发布者信息 -->
			<view class="info-card">
				<view class="card-title">发布者信息</view>
				<view class="publisher-card">
					<view class="publisher-row">
						<text class="publisher-label">发布者</text>
						<text class="publisher-name">{{ taskInfo.publisher_name || '未知用户' }}</text>
					</view>
					<view class="publisher-row">
						<text class="publisher-label">发布时间</text>
						<text class="publisher-time">{{ formatTime(taskInfo.publish_time) }}</text>
					</view>
				</view>
			</view>

			<!-- 接单人信息 -->
			<view class="info-card" v-if="shouldShowAccepterInfo(taskInfo)">
				<view class="card-title">接单人信息</view>
				<view class="accepter-card" :class="{ completed: taskInfo.order_status === 'completed' }" v-if="getAccepterInfo(taskInfo)">
					<view class="accepter-row">
						<text class="accepter-label">接单人</text>
						<text class="accepter-name">{{ getAccepterInfo(taskInfo).nickname || '未知用户' }}</text>
					</view>
					<view class="accepter-row" v-if="getAccepterInfo(taskInfo).phone">
						<text class="accepter-label">联系电话</text>
						<text class="accepter-phone">{{ getAccepterInfo(taskInfo).phone }}</text>
					</view>
					<view class="accepter-row" v-if="getAccepterInfo(taskInfo).accept_time">
						<text class="accepter-label">接单时间</text>
						<text class="accepter-time">{{ formatTime(getAccepterInfo(taskInfo).accept_time) }}</text>
					</view>
					<view class="accepter-row" v-if="taskInfo.order_status === 'completed' && (getAccepterInfo(taskInfo).complete_time || taskInfo.complete_time)">
						<text class="accepter-label">完成时间</text>
						<text class="accepter-time">{{ formatTime(getAccepterInfo(taskInfo).complete_time || taskInfo.complete_time) }}</text>
					</view>
					<view class="accepter-row" v-if="getAccepterInfo(taskInfo).status">
						<text class="accepter-label">状态</text>
						<text class="accepter-status" :class="getAccepterInfo(taskInfo).status">{{ getAccepterStatusText(getAccepterInfo(taskInfo).status) }}</text>
					</view>
				</view>
				<view class="no-accepter-tip" v-else>
					<text class="tip-text">暂无接单人信息</text>
				</view>
			</view>

			<!-- 支付信息 -->
			<view class="info-card" v-if="getTaskPaymentRecord(taskInfo)">
				<view class="card-title">支付信息</view>
				<view class="payment-card">
					<view class="payment-item">
						<view class="payment-header">
							<text class="payment-id">订单号：{{ getTaskPaymentRecord(taskInfo).payment_id }}</text>
							<text class="payment-type">{{ getPaymentTypeText(getTaskPaymentRecord(taskInfo).type) }}</text>
						</view>
						<view class="payment-info">
							<text class="payment-amount">¥{{ getTaskPaymentRecord(taskInfo).amount }}</text>
							<text class="payment-method">{{ getPaymentMethodText(getTaskPaymentRecord(taskInfo).payment_method) }}</text>
						</view>
						<view class="payment-status-info">
							<text class="payment-status-text" :class="getTaskPaymentRecord(taskInfo).status">{{ getPaymentStatusText(getTaskPaymentRecord(taskInfo).status) }}</text>
							<text class="payment-time" v-if="getTaskPaymentRecord(taskInfo).create_time">创建：{{ formatTime(getTaskPaymentRecord(taskInfo).create_time) }}</text>
							<text class="payment-time" v-if="getTaskPaymentRecord(taskInfo).pay_time">支付：{{ formatTime(getTaskPaymentRecord(taskInfo).pay_time) }}</text>
						</view>
						<!-- 退款信息 -->
						<view class="refund-info" v-if="getTaskPaymentRecord(taskInfo).refund_info && getTaskPaymentRecord(taskInfo).status === 'refunded'">
							<text class="refund-amount">退款：¥{{ getTaskPaymentRecord(taskInfo).refund_info.refund_amount }}</text>
							<text class="refund-reason" v-if="getTaskPaymentRecord(taskInfo).refund_info.refund_reason">原因：{{ getTaskPaymentRecord(taskInfo).refund_info.refund_reason }}</text>
						</view>
						<!-- 手续费信息 -->
						<view class="fee-info" v-if="getTaskPaymentRecord(taskInfo).platform_fee > 0">
							<text class="platform-fee">平台费：¥{{ getTaskPaymentRecord(taskInfo).platform_fee }}</text>
							<text class="actual-amount" v-if="getTaskPaymentRecord(taskInfo).actual_amount">实际：¥{{ getTaskPaymentRecord(taskInfo).actual_amount }}</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 时间线 -->
			<view class="info-card">
				<view class="card-title">时间节点</view>
				<view class="timeline-card">
					<view class="timeline-item">
						<view class="timeline-dot"></view>
						<view class="timeline-content">
							<text class="timeline-label">发布时间</text>
							<text class="timeline-time">{{ formatTime(taskInfo.publish_time) }}</text>
						</view>
					</view>
					<view class="timeline-item" v-if="getAccepterInfo(taskInfo) && getAccepterInfo(taskInfo).accept_time">
						<view class="timeline-dot active"></view>
						<view class="timeline-content">
							<text class="timeline-label">接单时间</text>
							<text class="timeline-time">{{ formatTime(getAccepterInfo(taskInfo).accept_time) }}</text>
						</view>
					</view>
					<view class="timeline-item" v-if="taskInfo.complete_time">
						<view class="timeline-dot completed"></view>
						<view class="timeline-content">
							<text class="timeline-label">完成时间</text>
							<text class="timeline-time">{{ formatTime(taskInfo.complete_time) }}</text>
						</view>
					</view>
					<view class="timeline-item" v-if="taskInfo.cancel_time">
						<view class="timeline-dot cancelled"></view>
						<view class="timeline-content">
							<text class="timeline-label">取消时间</text>
							<text class="timeline-time">{{ formatTime(taskInfo.cancel_time) }}</text>
							<text class="timeline-reason" v-if="taskInfo.cancel_reason">{{ taskInfo.cancel_reason }}</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 操作按钮 -->
			<view class="action-bar">
				<button class="action-btn" @click="goBack">返回列表</button>
				<button class="action-btn primary" v-if="taskInfo.order_status === 'waiting_payment'" @click="requestPayment">催促支付</button>
				<button class="action-btn primary" v-if="taskInfo.order_status === 'in_progress'" @click="completeTask">完成任务</button>
				<button class="action-btn warn" v-if="!isHistoryOrder(taskInfo)" @click="handleDispute">处理纠纷</button>
			</view>
		</view>
	</AdminLayout>
</template>

<script>
import AdminLayout from '@/components/AdminLayout.vue'

export default {
	components: { AdminLayout },
	data() {
		return {
			taskId: '',
			taskInfo: {},
			isLoading: false
		}
	},
	
	onLoad(options) {
		if (options.id) {
			this.taskId = options.id
			this.loadTaskDetail()
		} else {
			uni.showToast({ title: '缺少订单ID参数', icon: 'none' })
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
		}
	},
	
	methods: {
		// 加载订单详情
		async loadTaskDetail() {
			this.isLoading = true
			try {
				const { result } = await uniCloud.callFunction({
					name: 'getTaskDetail',
					data: {
						taskId: this.taskId,
						isAdmin: true
					}
				})
				
				if (result && result.code === 200) {
					this.taskInfo = result.data
					console.log('订单详情:', this.taskInfo)
				} else {
					throw new Error(result?.msg || '加载失败')
				}
			} catch (error) {
				console.error('加载订单详情失败:', error)
				uni.showToast({ title: '加载失败', icon: 'none' })
			} finally {
				this.isLoading = false
			}
		},
		
		// 时间格式化
		formatTime(v) {
			if (!v) return '--'
			const d = new Date(v)
			const p = n => String(n).padStart(2, '0')
			return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
		},
		
		// 从任务标题推断类型
		getTaskTypeFromTitle(title) {
			if (!title) return '其他'
			const titleLower = title.toLowerCase()
			
			if (titleLower.includes('代购') || titleLower.includes('买')) return '代购'
			if (titleLower.includes('出') || titleLower.includes('卖') || titleLower.includes('转让')) return '出物'
			if (titleLower.includes('快递') || titleLower.includes('包裹') || titleLower.includes('代取')) return '快递'
			if (titleLower.includes('外卖') || titleLower.includes('送餐')) return '外卖'
			
			return '其他'
		},
		
		// 获取订单状态文本
		getTaskOrderStatusText(status) {
			const statusMap = { 
				waiting_accept: '待接单',
				waiting_payment: '待支付',
				paid_pending: '已支付待接单',
				in_progress: '进行中',
				completed: '已完成',
				cancelled: '已取消',
				expired: '已过期',
				unknown: '未知状态'
			}
			return statusMap[status] || status
		},
		
		// 获取支付状态
		getPaymentStatus(task) {
			const hasPaid = task.audit_status !== undefined && task.audit_status !== null
			return hasPaid ? { text: '已支付', class: 'paid', status: 'success' } : { text: '未支付', class: 'unpaid', status: 'unpaid' }
		},
		
		// 判断是否显示接单人信息
		shouldShowAccepterInfo(task) {
			return task.order_status === 'in_progress' || task.order_status === 'completed'
		},
		
		// 获取接单人信息
		getAccepterInfo(task) {
			if (task.order_status !== 'in_progress' && task.order_status !== 'completed') {
				return null
			}
			
			if (task.receiver_id || task.receiver_name) {
				return {
					user_id: task.receiver_id,
					nickname: task.receiver_name,
					avatar: task.receiver_avatar || '',
					phone: task.contact_phone || '',
					accept_time: task.accept_time,
					complete_time: task.complete_time,
					cancel_time: task.cancel_time,
					status: task.order_status === 'completed' ? 'completed' : 'active'
				}
			}
			
			if (task.participants && task.participants.length > 0) {
				const accepter = task.participants.find(p => p.status === 'active') || task.participants[0]
				return accepter
			}
			
			return null
		},
		
		// 获取接单人状态文本
		getAccepterStatusText(status) {
			const statusMap = {
				'active': '正在进行',
				'completed': '已完成任务',
				'cancelled': '已取消',
				'pending': '待确认'
			}
			return statusMap[status] || status || '未知状态'
		},
		
		// 获取支付记录
		getTaskPaymentRecord(task) {
			const hasPaid = task.audit_status !== undefined && task.audit_status !== null
			
			if (!hasPaid) {
				return null
			}
			
			return {
				payment_id: task.payment_id || `AUDIT_${task._id}`,
				type: 'task_publish',
				amount: task.payment_amount || task.reward,
				status: 'success',
				payment_method: task.payment_method || 'wechat',
				create_time: task.payment_time || task.publish_time,
				pay_time: task.payment_time || task.publish_time,
				update_time: task.payment_time || task.publish_time,
				user_id: task.publisher_id,
				audit_status: task.audit_status,
				platform_fee: task.platform_fee || 0,
				actual_amount: task.actual_amount || 0,
				refund_info: task.refund_info || null
			}
		},
		
		// 获取支付状态文本
		getPaymentStatusText(status) {
			const statusMap = {
				'success': '支付成功',
				'pending': '支付中',
				'failed': '支付失败',
				'cancelled': '支付取消',
				'refunded': '已退款'
			}
			return statusMap[status] || status || '未知状态'
		},
		
		// 获取支付类型文本
		getPaymentTypeText(type) {
			const typeMap = {
				'task_publish': '任务发布',
				'task_reward': '任务悬赏',
				'recharge': '账户充值',
				'withdraw': '提现',
				'refund': '退款',
				'other': '其他'
			}
			return typeMap[type] || type || '未知类型'
		},
		
		// 获取支付方式文本
		getPaymentMethodText(method) {
			const methodMap = {
				'wallet': '钱包支付',
				'wechat': '微信支付',
				'alipay': '支付宝',
				'bank_card': '银行卡'
			}
			return methodMap[method] || method || '未知方式'
		},
		
		// 判断是否为历史订单
		isHistoryOrder(task) {
			return task.order_status === 'completed' || task.order_status === 'cancelled' || task.order_status === 'expired'
		},
		
		// 返回列表
		goBack() {
			uni.navigateBack()
		},
		
		// 催促支付
		async requestPayment() {
			const confirmed = await this.confirm(`是否向发布者发送支付提醒？\n任务：${this.taskInfo.title}`)
			if (!confirmed) return
			
			try {
				uni.showLoading({ title: '发送中...' })
				
				const { result } = await uniCloud.callFunction({
					name: 'createChatMessage',
					data: {
						taskId: this.taskInfo._id,
						messageType: 'system',
						senderId: 'payment_admin',
						receiverId: this.taskInfo.publisher_id,
						content: `您好，您发布的任务"${this.taskInfo.title}"还未完成支付，请及时支付以确保任务正常进行。如有疑问请联系客服。`,
						title: '支付提醒',
						extraData: {
							isOfficial: true,
							messageCategory: 'payment_reminder',
							taskInfo: {
								taskId: this.taskInfo._id,
								taskTitle: this.taskInfo.title,
								reward: this.taskInfo.reward
							}
						}
					}
				})
				
				uni.hideLoading()
				
				if (result && result.code === 200) {
					uni.showToast({ title: '支付提醒已发送', icon: 'success' })
				} else {
					throw new Error(result?.msg || '发送失败')
				}
			} catch (error) {
				uni.hideLoading()
				console.error('发送支付提醒失败:', error)
				uni.showToast({ title: '发送失败，请重试', icon: 'none' })
			}
		},
		
		// 完成任务
		completeTask() {
			uni.showModal({
				title: '完成任务',
				content: `确认将任务标记为已完成？\n任务：${this.taskInfo.title}`,
				confirmText: '确认完成',
				success: (res) => {
					if (res.confirm) {
						uni.showToast({ title: '任务已完成', icon: 'success' })
						this.loadTaskDetail()
					}
				}
			})
		},
		
		// 处理纠纷
		handleDispute() {
			uni.navigateTo({
				url: `/pages/admin/order-management/index?taskId=${this.taskId}&action=dispute`
			})
		},
		
		// 确认对话框
		confirm(message) {
			return new Promise((resolve) => {
				uni.showModal({
					title: '确认操作',
					content: message,
					success: (res) => resolve(res.confirm)
				})
			})
		}
	}
}
</script>

<style scoped>
.page {
	padding: 20rpx;
	min-height: calc(100vh - 140rpx);
}

.section-header {
	margin-bottom: 30rpx;
}

.section-title {
	font-size: 36rpx;
	font-weight: 600;
	color: #333;
	display: block;
	margin-bottom: 8rpx;
}

.section-desc {
	font-size: 26rpx;
	color: #666;
	display: block;
}

/* 信息卡片 */
.info-card {
	background: #fff;
	border-radius: 16rpx;
	padding: 24rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.06);
}

.card-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 20rpx;
	padding-bottom: 12rpx;
	border-bottom: 2rpx solid #f0f0f0;
}

.info-grid {
	display: grid;
	grid-template-columns: repeat(2, 1fr);
	gap: 20rpx;
}

.info-item {
	display: flex;
	flex-direction: column;
	gap: 8rpx;
}

.info-label {
	font-size: 24rpx;
	color: #999;
}

.info-value {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
}

.type-tag {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: #fff;
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
	font-size: 24rpx;
	display: inline-block;
	align-self: flex-start;
}

.reward-value {
	color: #ff6b35;
	font-size: 32rpx;
	font-weight: 700;
}

.status-tag, .payment-tag {
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
	font-size: 24rpx;
	font-weight: 600;
	display: inline-block;
	align-self: flex-start;
}

.status-tag.waiting_accept { background: #cff4fc; color: #055160; }
.status-tag.waiting_payment { background: #fff3cd; color: #856404; }
.status-tag.in_progress { background: #cce5ff; color: #0066cc; }
.status-tag.completed { background: #d4edda; color: #155724; }
.status-tag.cancelled { background: #f8d7da; color: #721c24; }

.payment-tag.paid { background: #d4edda; color: #155724; }
.payment-tag.unpaid { background: #fff3cd; color: #856404; }

.description-content {
	font-size: 28rpx;
	color: #555;
	line-height: 1.6;
	background: #f8f9fa;
	padding: 20rpx;
	border-radius: 12rpx;
}

.publisher-card, .accepter-card, .payment-card, .timeline-card {
	background: #f8f9fa;
	border-radius: 12rpx;
	padding: 20rpx;
	border-left: 4rpx solid #007aff;
}

.accepter-card {
	border-left-color: #52c41a;
}

.publisher-row, .accepter-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 12rpx;
}

.publisher-row:last-child, .accepter-row:last-child {
	margin-bottom: 0;
}

.publisher-label, .accepter-label {
	font-size: 26rpx;
	color: #666;
	font-weight: 500;
}

.publisher-name, .publisher-time, .accepter-name, .accepter-phone, .accepter-time {
	font-size: 28rpx;
	color: #333;
	font-weight: 600;
}

.accepter-name {
	color: #52c41a;
}

.accepter-phone {
	color: #1890ff;
	font-family: monospace;
}

.accepter-status {
	font-size: 24rpx;
	font-weight: 600;
	padding: 6rpx 12rpx;
	border-radius: 12rpx;
}

.accepter-status.active {
	background: #d4edda;
	color: #155724;
}

.accepter-status.completed {
	background: #cce5ff;
	color: #0066cc;
}

.no-accepter-tip {
	background: #f8f9fa;
	border-radius: 12rpx;
	padding: 32rpx;
	text-align: center;
	border: 2rpx dashed #e0e0e0;
}

.tip-text {
	font-size: 28rpx;
	color: #999;
	font-style: italic;
}

/* 支付信息 */
.payment-item {
	display: flex;
	flex-direction: column;
	gap: 12rpx;
}

.payment-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding-bottom: 8rpx;
	border-bottom: 1rpx solid #e0e0e0;
}

.payment-id {
	font-size: 24rpx;
	color: #666;
	font-family: monospace;
}

.payment-type {
	font-size: 22rpx;
	color: #007aff;
	background: #e6f7ff;
	padding: 4rpx 8rpx;
	border-radius: 8rpx;
}

.payment-info {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.payment-amount {
	font-size: 32rpx;
	font-weight: 700;
	color: #52c41a;
}

.payment-method {
	font-size: 26rpx;
	color: #333;
	font-weight: 600;
}

.payment-status-info {
	display: flex;
	justify-content: space-between;
	align-items: center;
	flex-wrap: wrap;
	gap: 8rpx;
}

.payment-status-text {
	font-size: 24rpx;
	font-weight: 600;
	padding: 6rpx 12rpx;
	border-radius: 12rpx;
}

.payment-status-text.success {
	background: #d4edda;
	color: #155724;
}

.payment-time {
	font-size: 22rpx;
	color: #999;
}

.refund-info, .fee-info {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 10rpx 16rpx;
	border-radius: 8rpx;
	margin-top: 8rpx;
}

.refund-info {
	background: #fff2f0;
	border: 1rpx solid #ffccc7;
}

.fee-info {
	background: #f6ffed;
	border: 1rpx solid #d9f7be;
}

.refund-amount, .refund-reason {
	font-size: 22rpx;
	color: #ff4d4f;
}

.platform-fee, .actual-amount {
	font-size: 22rpx;
	color: #52c41a;
}

/* 时间线 */
.timeline-item {
	display: flex;
	align-items: flex-start;
	margin-bottom: 20rpx;
	position: relative;
}

.timeline-item:last-child {
	margin-bottom: 0;
}

.timeline-item:not(:last-child)::after {
	content: '';
	position: absolute;
	left: 15rpx;
	top: 32rpx;
	bottom: -20rpx;
	width: 2rpx;
	background: #e0e0e0;
}

.timeline-dot {
	width: 30rpx;
	height: 30rpx;
	border-radius: 50%;
	background: #e0e0e0;
	margin-right: 16rpx;
	flex-shrink: 0;
	margin-top: 4rpx;
}

.timeline-dot.active {
	background: #52c41a;
}

.timeline-dot.completed {
	background: #1890ff;
}

.timeline-dot.cancelled {
	background: #ff4d4f;
}

.timeline-content {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 4rpx;
}

.timeline-label {
	font-size: 26rpx;
	color: #666;
}

.timeline-time {
	font-size: 28rpx;
	color: #333;
	font-weight: 600;
}

.timeline-reason {
	font-size: 24rpx;
	color: #ff4d4f;
	font-style: italic;
}

/* 操作按钮栏 */
.action-bar {
	display: flex;
	gap: 16rpx;
	justify-content: flex-end;
	margin-top: 20rpx;
	padding: 20rpx;
	background: #fff;
	border-radius: 16rpx;
	box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.06);
}

.action-btn {
	padding: 16rpx 32rpx;
	border-radius: 12rpx;
	font-size: 28rpx;
	border: none;
	font-weight: 500;
	transition: all 0.3s;
}

.action-btn {
	background: #f5f5f5;
	color: #666;
}

.action-btn.primary {
	background: linear-gradient(135deg, #007aff 0%, #0056cc 100%);
	color: #fff;
}

.action-btn.warn {
	background: linear-gradient(135deg, #ff9500 0%, #e6840e 100%);
	color: #fff;
}

/* 响应式 */
@media (max-width: 750rpx) {
	.info-grid {
		grid-template-columns: 1fr;
	}
	
	.action-bar {
		flex-direction: column;
	}
}
</style>

